package com.ultrapower.ctool.view;

import android.app.ActionBar;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ultrapower.ctool.AppContext;
import com.ultrapower.ctool.ConfUtils;
import com.ultrapower.ctool.bean.SearchTestBean;
import com.ultrapower.ctool.bean.WangGeVO;
import com.ultrapower.ctool.core.CustomApplication;
import com.ultrapower.ctool.model.RegisterRolePirVO;
import com.ultrapower.ctool.xn_app.JingYingActivity;
import com.ultrapower.ctool.xn_app.R;
import com.ultrapower.ctool.xn_app.WangGeActivity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by ctool on 2017/5/10.
 */

public class WangGePopWindow extends PopupWindow implements SearchView.SearchViewListener {
    private View contentView;//页面
    private Context context;//上下文
    private View noView;
    private WangGeActivity activity;
    private Spinner stype_wg_search;//事件类型
    private Spinner step_wg_search;//事件步骤
    private WangGeVO wgVO = new WangGeVO();
    ;//参数
    private String wgName;
    private SearchView searchView;//搜索view
    private ArrayAdapter<String> autoCompleteAdapter;//自动补全列表adapter
    private List<SearchTestBean> dbData;//数据库数据，总数据
    private List<String> autoCompleteData;//搜索过程中自动补全数据

    private static final List stypes = new ArrayList<RegisterRolePirVO>();
    private static final List steps = new ArrayList<RegisterRolePirVO>();
    private ArrayAdapter<String> stypeAdapter;
    private ArrayAdapter<String> stepAdapter;

    private static int DEFAULT_HINT_SIZE = 5;//默认提示框显示项的个数
    private static int hintSize = DEFAULT_HINT_SIZE;//提示框显示项的个数
    //private OkHttpClient client = new OkHttpClient();
    private Gson gson = new Gson();
    Map<String, SearchTestBean> dbMap = new HashMap<String, SearchTestBean>();
    private CustomApplication application;
    private TextView filterReset;//重置
    private TextView filterSure;//确定
    private AdapterView.OnItemSelectedListener OnCatSpinnerCL = new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            ((TextView) parent.getChildAt(0)).setTextColor(Color.BLACK);
            ((TextView) parent.getChildAt(0)).setTextSize(18);
        }

        public void onNothingSelected(AdapterView<?> parent) {

        }
    };

    public static void setHintSize(int hintSize) {//设置提示框显示项的个数
        WangGePopWindow.hintSize = hintSize;
    }

    static {
        steps.add(new RegisterRolePirVO("", ""));
        steps.add(new RegisterRolePirVO("1", "保存事件"));
        steps.add(new RegisterRolePirVO("2", "处理事件"));
        steps.add(new RegisterRolePirVO("3", "验收事件"));
        stypes.add(new RegisterRolePirVO("", ""));
        stypes.add(new RegisterRolePirVO("1", "一般隐患"));
        stypes.add(new RegisterRolePirVO("2", "重大隐患"));
        stypes.add(new RegisterRolePirVO("3", "违法生产经营行为"));
        stypes.add(new RegisterRolePirVO("4", "其他安全生产"));

    }

    public WangGePopWindow(Activity context, final Handler handler, CustomApplication application, WangGeActivity activity) {
        this.application = application;
        this.context = context;
        this.activity = activity;
        initViews(handler);
        initData();
    }

    /**
     * 初始化视图
     */
    private void initViews(final Handler handler) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);//加载布局
        contentView = inflater.inflate(R.layout.pop_wangge_details, null);//弹框界面
        searchView = (SearchView) contentView.findViewById(R.id.wg_search_grid);
        //设置监听
        searchView.setSearchViewListener(this);
        //设置adapter
//        searchView.setTipsHintAdapter(hintAdapter);
        searchView.setAutoCompleteAdapter(autoCompleteAdapter);
        noView = contentView.findViewById(R.id.popup_wangge_noview);//关闭弹框
        stype_wg_search = (Spinner) contentView.findViewById(R.id.stype_wg_search);
        step_wg_search = (Spinner) contentView.findViewById(R.id.step_wg_search);
        filterReset = (TextView) contentView.findViewById(R.id.filter_reset_wg);//重置
        filterSure = (TextView) contentView.findViewById(R.id.filter_sure_wg);//确定
        noView.setOnClickListener(new WangGePopWindow.CancelOnClickListener());
        contentView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
                    dismiss();
                }
                return true;
            }
        });


        // 重置的点击监听，将所有选项全设为false
        filterReset.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                searchView.getEtInput().setText("");
                searchView.getIvDelete().setVisibility(View.GONE);
                stype_wg_search.setSelection(0);
                step_wg_search.setSelection(0);
                wgVO.setStep("");
                wgVO.setStype("");
                wgVO.setWgName("");
            }
        });
        // 确定的点击监听，将所有已选中项列出
        filterSure.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (!"".equals(wgName)) {
                    wgVO.setWgName(wgName);
                }
                if(stype_wg_search.getSelectedItem()!=null) {
                    wgVO.setStype(((RegisterRolePirVO) stype_wg_search.getSelectedItem()).getId());
                }
                if(step_wg_search.getSelectedItem()!=null){
                    wgVO.setStep(((RegisterRolePirVO) step_wg_search.getSelectedItem()).getId());
                }
                Message msg = new Message();
                Bundle data = new Bundle();
                data.putSerializable("wgVO", wgVO);
                msg.setData(data);
                msg.what = 1;
                handler.sendMessage(msg);
                dismiss();
            }
        });

        //将可选内容与ArrayAdapter连接起来
        //stypeAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, stypes);
        //设置下拉列表的风格
        //stypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //将adapter 添加到spinner中
       // stype_wg_search.setAdapter(stypeAdapter);
        //添加事件Spinner事件监听
       // stype_wg_search.setOnItemSelectedListener(new StypeSpinnerSelectedListener());
        //设置默认值
       // stype_wg_search.setVisibility(View.VISIBLE);

        //将可选内容与ArrayAdapter连接起来
       // stepAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, steps);
        //设置下拉列表的风格
       // stepAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //将adapter 添加到spinner中
       // step_wg_search.setAdapter(stepAdapter);
        //添加事件Spinner事件监听
        //step_wg_search.setOnItemSelectedListener(new StepSpinnerSelectedListener());
        //设置默认值
       // step_wg_search.setVisibility(View.VISIBLE);

        this.setContentView(contentView);
        this.setWidth(ActionBar.LayoutParams.MATCH_PARENT);
        this.setHeight(ActionBar.LayoutParams.MATCH_PARENT);
        ColorDrawable dw = new ColorDrawable(00000000);
        this.setBackgroundDrawable(dw);
        this.setFocusable(true);
        this.setOutsideTouchable(false);
        this.update();

    }

    /*
        //使用数组形式操作
        class StypeSpinnerSelectedListener implements AdapterView.OnItemSelectedListener {

            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
                                       long arg3) {
                wgVO.setStype(stypes[arg2]);
            }

            public void onNothingSelected(AdapterView<?> arg0) {
            }
        }

        //使用数组形式操作
        class StepSpinnerSelectedListener implements AdapterView.OnItemSelectedListener {

            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
                                       long arg3) {
                wgVO.setStep(steps[arg2]);
            }

            public void onNothingSelected(AdapterView<?> arg0) {
            }
        }
    */
    public class CancelOnClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            dismiss();
        }
    }

    public boolean onKeyDown(Context context, int keyCode, KeyEvent event) {
        this.context = context;
        if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
            dismiss();
        }
        return true;
    }

    public void showFilterPopup(View parent) {
        if (!this.isShowing()) {
            this.showAsDropDown(parent);
        } else {
            this.dismiss();
        }
    }

    /**
     * 初始化数据
     */
    private void initData() {
        //从数据库获取数据
        getDbData();
        //初始化自动补全数据
        getAutoCompleteData(null);
    }

    /**
     * 获取db 数据
     */
    private void getDbData() {
        System.out.println("-----------------------0");
        dbData = new ArrayList<>();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = new FormBody.Builder()
                            .add("field", "gid")
                            .add("code", "c_aj_wgsj")
                            .add("userId", String.valueOf(application.getLoginUser().getLogin_id()))
                            .build();
                    Request request = new Request.Builder().url(ConfUtils.SERVICE_URL + "widget/findJson").post(requestBody).build();
                    Response response = null;

                    response = client.newCall(request).execute();

                    if (response.isSuccessful()) {//成功
                        String result = response.body().string();
                        Map<String, Object> resultMap = gson.fromJson(result, Map.class);
                        // 初始数据库表
                        List<Map<String, Object>> list = (List<Map<String, Object>>) resultMap.get("rows");
                        for (Map<String, Object> li : list) {
                            SearchTestBean searchTestBean = new SearchTestBean((String) li.get("xid"), (String) li.get("aname"), "", "");
                            dbData.add(searchTestBean);
                            dbMap.put((String) li.get("aname"), searchTestBean);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    ArrayAdapter<RegisterRolePirVO> aradapter = new ArrayAdapter<RegisterRolePirVO>(context, android.R.layout.simple_spinner_item, stypes);
                    aradapter.setDropDownViewResource(R.layout.simple_dropdown_item_1line);
                    stype_wg_search.setAdapter(aradapter);
                    stype_wg_search.setOnItemSelectedListener(OnCatSpinnerCL);
                    ArrayAdapter<RegisterRolePirVO> stepsaradapter = new ArrayAdapter<RegisterRolePirVO>(context, android.R.layout.simple_spinner_item, steps);
                    stepsaradapter.setDropDownViewResource(R.layout.simple_dropdown_item_1line);
                    step_wg_search.setAdapter(stepsaradapter);
                    step_wg_search.setOnItemSelectedListener(OnCatSpinnerCL);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 获取自动补全data 和adapter
     */
    private void getAutoCompleteData(String text) {
        if (autoCompleteData == null) {
            //初始化
            autoCompleteData = new ArrayList<>(hintSize);
        } else {
            // 根据text 获取auto data
            autoCompleteData.clear();
            for (int i = 0, count = 0; i < dbData.size()
                    && count < hintSize; i++) {
                if (dbData.get(i).getTitle().contains(text.trim())) {
                    autoCompleteData.add(dbData.get(i).getTitle());
                    count++;
                }
            }
        }
        if (autoCompleteAdapter == null) {
            autoCompleteAdapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, autoCompleteData);
        } else {
            autoCompleteAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 当搜索框 文本改变时 触发的回调 ,更新自动补全数据
     *
     * @param text
     */
    @Override
    public void onRefreshAutoComplete(String text) {
        //更新数据
        getAutoCompleteData(text);
    }

    /**
     * 点击搜索键时edit text触发的回调
     *
     * @param text
     */
    @Override
    public void onSearch(String text) {
        wgName = text;
    }
}
